package com.tma.demo;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class SlideShow {

    private RefreshHandler mRefreshHandler;

    public SlideShow(Context context, ImageView imageview) {
        mRefreshHandler = new RefreshHandler(context, imageview);
    }

    public void play() {
        mRefreshHandler.play();
    }

    public void stop() {
        mRefreshHandler.stop();
    }

    private static class RefreshHandler extends Handler {

        private int mIndex = 0;

        private int mImgIds[] = { R.drawable.scenery1, R.drawable.scenery2,
                R.drawable.scenery3, R.drawable.scenery4, R.drawable.scenery5,
                R.drawable.scenery6, R.drawable.scenery7 };

        private ImageView mImageView;
        private Animation mAnimation;
        private long mInterval = 2;
        private boolean mIsPlay = false;

        public RefreshHandler(Context context, ImageView imageview) {
            mImageView = imageview;
            mAnimation = AnimationUtils.loadAnimation(context, R.anim.l2r);
        }

        @Override
        public void handleMessage(Message msg) {
            if (!mIsPlay) {
                return;
            }

            if (mIndex >= mImgIds.length) {
                mIndex = 0;
            }

            mImageView.startAnimation(mAnimation);
            mImageView.setImageResource(mImgIds[mIndex]);
            mIndex++;

            next();

        }

        public void play() {
            mIndex = 0;
            mIsPlay = true;
            next();
        }

        public void stop() {
            mIsPlay = false;
        }

        private void next() {
            Message msg = Message.obtain();
            sendMessageDelayed(msg, mInterval * 1000);
        }
    }

}
